package cn.maihe.elg.operation.supports.electronicseal.kt.mixca;

import cn.maihe.elg.operation.config.ElgResourceConfig;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping(value = "/mixCaSign")
@Slf4j
public class MixCaSignController {

    @Resource
    private ElgResourceConfig elgResourceConfig;
    @Resource
    private ElgResourceService elgResourceService;

    @Resource
    private MixCaSignService mixCaSignService;


    @RequestMapping(value = "/caCallback/upload", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> caCallbackUploadFile(HttpServletRequest request) {

        Map<String, String> reMap = new HashMap<>();
        try {
            String acceptOrderNo = request.getParameter("params");
            log.info("params=acceptOrderNo:{} << ", acceptOrderNo);

            Map<String, byte[]> map = new HashMap<>();
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 上传文件属性name必须为文件类型
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (file != null) {
                        byte[] by = null;
                        try {
                            by = file.getBytes();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (by != null && by.length > 0) {
                            map.put(file.getName().toLowerCase(), by);
                        }
                    }
                }
            }
            if (!map.containsKey("pdf")) {
                throw new RuntimeException("未回传pdf文件");
            }
            Path signedEdcPath = null;
            if (map.containsKey("edc")) {
                signedEdcPath = elgResourceService.buildSaveAbsolutePath("ofd", acceptOrderNo, "已签章担保保函申请书", "edc");
            }

            Path signedPdfPath = elgResourceService.buildSaveAbsolutePath("ofd", acceptOrderNo, "已签章担保保函申请书", "pdf");

            try {
                byte[] pdfBytes = map.get("pdf");
                Files.copy(new ByteArrayInputStream(pdfBytes), signedPdfPath, StandardCopyOption.REPLACE_EXISTING);
                if (signedEdcPath != null) {
                    byte[] edcBytes = map.get("edc");
                    Files.copy(new ByteArrayInputStream(edcBytes), signedEdcPath, StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (Exception e) {
                throw new RuntimeException("保存回传签章文件异常:" + e.getMessage(), e);
            }

            mixCaSignService.saveSignedApplyFile(acceptOrderNo, signedPdfPath, signedEdcPath);

            //1成功 0失败
            reMap.put("status", "1");
            reMap.put("msg", "上传成功");
        } catch (Exception e) {
            reMap.put("status", "0");
            reMap.put("msg", "上传失败：" + StringUtils.truncate(e.getMessage(), 50));
            log.error("融合签章上传失败：{}", e.getMessage(), e);
        }

        log.info("签署文件上传响应报文：{}", JSON.toJSONString(reMap));

        return reMap;
    }


}
